package com.glowworms.core.web.handler;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import com.glowworms.core.util.WebUtils;
import com.glowworms.core.web.bind.RequestAndResponse;

/**
 * 数据绑定失败
 */
public class DataBindingExceptionResolver extends AbstractHandlerExceptionResolver {

	
	/**
	 * 
	 */
	@Override
	protected boolean shouldApplyTo(HttpServletRequest request, Object handler) {
		return true;
	}
	
	/**
	 * 
	 */
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		if(ex instanceof BindException){
			RequestAndResponse requestAndResponse = new RequestAndResponse(request, response);
			if(WebUtils.isAjaxRequest(request)){
				//TODO: 定义错误格式
				return requestAndResponse.toJSONView();
			}
			else{
				//TODO: 得返回原提交的网站
				return requestAndResponse.toTemplateView();
			}
		}
		return null;
	}

}
